/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */
import React, {Component} from 'react';
import {
    Platform,
    StyleSheet,
    Text,
    View,
    Dimensions,
    TextInput,
    BackHandler
} from 'react-native';
import LoginLeaf from "./LoginLeaf";
import WaitingLeaf from "./WaitingLeaf";

let widthOfMargin = Dimensions.get("window").width * 0.05;

export default class App extends Component<{}> {
    constructor(props) {
        super(props);
        this.state = {
            currentScene: 'Login',
            phoneNumber: '',
            userPasswd: ''
        };
        this.onLoginPressed = this.onLoginPressed.bind(this);
        this.handleBackAction = this.handleBackAction.bind(this);
    }

    onLoginPressed(number, passwd) {
        this.setState({
            currentScene: 'Waiting', // 一旦使用setState，就会导致界面重新渲染，然后进入WaitingLeaf界面。
            phoneNumber: number,
            userPasswd: passwd
        });
    }

    render() {
        if (this.state.currentScene === 'Login') {
            // 返回 LoginLeaf组件
            // 给LoginLeaf组件提供onLoginPressed属性
            return <LoginLeaf onLoginPressed={this.onLoginPressed}/>
        } else {
            return <WaitingLeaf phoneNumber={this.state.phoneNumber}
                                userPasswd={this.state.userPasswd}
                                onBackAction={this.handleBackAction}/>
        }
    }

    handleBackAction() {
        if (this.state.currentScene === 'Waiting') {
            this.setState({currentScene: 'Login'});
            return true;
        }
        return false;
    }

    componentDidMount() {
        if (Platform.OS === 'android') {
            BackHandler.addEventListener('hardwareBackPress', this.handleBackAction);
        }
    }

    componentWillUnmount() {
        if (Platform.OS === 'android') {
            BackHandler.removeEventListener('hardwareBackPress', this.handleBackAction);
        }
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
    },
    textInputStyle: {
        width: 200,
        margin: widthOfMargin,
        backgroundColor: '#537741',
        fontSize: 20,
        textAlign: 'left'
    },
    bigTextPrompt: {
        width: 200,
        margin: widthOfMargin,
        backgroundColor: '#1746cd',
        color: 'white',
        textAlign: 'center',
        fontSize: 30
    }
});
